<?php


namespace app\admin\model;

use app\admin\model\Common;
use think\Exception;
use think\facade\Db;
use think\model\concern\SoftDelete;
use app\common\traits\ActionRecordTrait;
use app\common\traits\UserInfoTrait;

/**
 * 销售政策model
 * Class sales_policy
 * @package app\admin\model
 * @author Mr.Liu
 * @create 2021-09-15 15:01
 */
class Policy extends Common
{
    use SoftDelete;
    use ActionRecordTrait,UserInfoTrait;

    /**
     * 表名
     * @var string
     */
    protected $name = 'policy';
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名






    /**
     * 获取销售政策列表
     * 是否不分页  no_page  0/null 分页 1不分页
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu
     * @create 2021-05-26 10:51
     */
    public function getDataList(array $request): array
    {
        try {
            $request = $this->fmtRequest($request);
            $map     = $request['map'] ?? [];
            $where = [];
                $search = isset($map['search']) && $map['search'] ? trim($map['search']) : ''; // 促销政策名称
                if ($search) {
                    // 促销政策名称
                    array_push($where, ['sales_policy_name', 'like', '%' . $search . '%']);
                }
                $code = isset($map['code']) && $map['code'] ? trim($map['code']) : ''; // 促销政策编码
                if ($code) {
                    // 促销政策编码
                    array_push($where, ['sales_policy', 'like', '%' . $code . '%']);
                }
            $dataCount  = $this->where($where)->count();
            if ($dataCount) {
                // 订单列表
                $field = ['id','sales_policy', 'sales_policy_name', 'sales_policy_desc'];
                $list = $this->when(!(isset($map['no_page']) && $map['no_page']) ,function($query) use ($request){
                    $query->limit(($request['page'] - 1) * $request['limit'], $request['limit']);
                })->where($where)
                    ->order('id DESC')
                    ->field($field)->select()->toArray();
            }
            //$permission = get_user_permission_menu($userId,'order_list_tag');

            $data              = [];
            //$data['menu_list'] = $permission ? $permission : [];
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            return $data;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }
    }


    /**
     * 销售政策详情
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-09-20 16:25
     */
    public function getDataDetail(array $request): array
    {
        $goodsDetail = [];
        try {
            $id = $request['id'] ?? 0;
            if(!$id){
                $this->error = '请输入销售政策id';
                return [];
            }
            $goodsField = $request['coupon_field'] ?? '';
            if(!$goodsField){
                $goodsField = ['*'];
            }
            $detail = self::field($goodsField)->find($id);
            if($detail){
                $goodsDetail = $detail->toArray();
                $goodsDetail['category_name'] = Db::name('shop_goods_category')->where('id',$goodsDetail['category_id'])->value('name');
                if(isset($goodsDetail['create_user_id'])){
                    $goodsDetail['create_user_name'] = $this->getUserValue($goodsDetail['create_user_id'],'realname');
                }
            }
            return $goodsDetail;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }
    }

    /**
     * 新增销售政策
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Li
     * @create 2021-05-26 11:25
     */
    public function addData(array $request): bool
    {
        try {
            $validate = new \app\admin\validate\Policy();
            if (!$validate->scene('create')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }
        }catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
        Db::startTrans();
        try {
            $request['status'] =  $request['status'] ?? 0;
            $time = time();
            // 验证
            $data = [
                'sales_policy'                  => trim($request['sales_policy']),
                'sales_policy_name'             => trim($request['sales_policy_name']),
                'sales_policy_desc'           =>  isset($request['sales_policy_desc']) ? $request['sales_policy_desc'] : '',
                'create_user_id'        => $request['user']['id'],
                'status'                => 1,
                'update_time'           => $time,
                'create_time'           => $time
            ];
            $this->create($data);
            Db::commit();
            $this->error = '添加成功';
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
        $this->error = '添加失败';
        return false;

    }

    /**
     * 更新销售政策
     * @param array $request 请求参数
     * @return bool
     * @author Mr.Li
     * @create 2021-05-26 11:33
     */
    public function saveData(array $request): bool
    {
        // 验证
        try{
            $validate = new \app\admin\validate\Policy();
            if (!$validate->scene('update')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }
        }catch(\Exception $e){
            $this->error =$e->getMessage();
            return false;
        }
        $id = $request['id'] ?? 0;
        Db::startTrans();
        try {
            $goods = $this->field('id')->find($id);
            if($goods){
                $goods = $goods->toArray();
            }else{
                $this->error = '销售政策不存在';
                return false;
            }
            $time = time();
            $request['status'] =  $request['status'] ?? 2;
            $request['is_project'] =  $request['is_project'] ?? 1;
            $data = [
                'sales_policy'                  => trim($request['sales_policy']),
                'sales_policy_name'             => trim($request['sales_policy_name']),
                'sales_policy_desc'           =>  isset($request['sales_policy_desc']) ? $request['sales_policy_desc'] : '',
                'status'                => 1,
                'update_time'           => $time
                ];

            $this->where(['id'=>$id])->update($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
        $this->error = '更新失败';
        return false;
    }

    /**
     * 删除销售政策
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Li
     * @create 2021-05-26 15:09
     */
    public function deleteData(array $request): bool
    {
        try {

            $requestId = isset($request['id']) && $request['id'] ? $request['id'] : [];
            if (!$requestId) {
                $this->error = '参数错误';
                return false;
            }
            $idArr = is_array($requestId) ? $requestId : explode(',', $requestId);
            $where = [
                ['id', 'in', $idArr]
            ];
            Db::startTrans();
            $bool = self::destroy(function($query) use ($where){
                $query->where($where);
            });
            if ($bool) {
                Db::commit();
            }else{
                Db::rollback();
                $this->error = '删除失败';
                return false;
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
        $this->error = '删除成功';
        return true;
    }

    /**
     * 更新销售政策的上下架状态
     * @param array $request
     * @return bool
     * @author Mr.Li
     * @create 2021-06-03 11:12
     */
    public function updateStatus(array $request): bool
    {

        $bool = false;
        $requestId = isset($request['id']) && $request['id'] ? $request['id'] : [];
        if (!$requestId) {
            $this->error = '销售政策id不存在';
            return false;
        }
        $status = $request['status'] ?? 0;
        if (!$status || !in_array($status,[1,2])) {
            $this->error = '上下架状态不正确';
            return false;
        }
        $idArr = is_array($requestId) ? $requestId : explode(',', $requestId);
        $where = [
            ['id', 'in', $idArr]
        ];
        $content = '';
        try{
            if($status == 1){//上架
                $bool =  Db::name('shop_goods')->where($where)->update(['status' => 1]);
                $content .= '更新产品上下架状态：【下架】 -> 【上架】 ';
            }elseif($status == 2){//下架
                $bool = Db::name('shop_goods')->where($where)->update(['status' => 2]);
                $content .= '更新产品上下架状态：【上架】 -> 【下架】 ';
            }
            if($bool){
                foreach($idArr as $id){
                    $this->addActionRecord($request['user']['id'],'shop_goods_updateStatus',$id,$content,'shop','goods');
                }
                $this->error = '更新成功';
                return true;
            }

        }catch (\Exception $e) {
        }
        $this->error = '更新失败';
        return $bool;

    }
    

    /**
     * 根据条件获取信息
     * @param  array $where 查询条件
     * @param  array $field 查询字段
     * @return array
     * @author Mr.Liu 
     * @create 2021-09-20 10:51
     */
    public function getGoodsList(array $where = [], array $field = []): array
    {
        try {
            $list = $this->where($where)->field($field)->select()->toArray();
        } catch (\Exception $e) {
        }

        return isset($list) && $list ? $list : [];
    }


    /**
     * 更新同步金蝶销售政策库存
     * @author Mr.Li
     * @create 2021-07-08 16:52
     */
    public function syncKingdeeStock()
    {
        try {

            $sqlserverConn =  \think\facade\Db::connect('sqlsrv');
            $sql = "exec proc_Dxj_kxkc 'kc'";
            //$sql = "exec DXJ_WLDWHS  'wl'";
            $sqlRes = $sqlserverConn->query($sql);
            $sqlRes = $sqlRes[0] ?? [];
            //print_r($sqlRes);
            if($sqlRes){
                foreach($sqlRes as $v){
                    $insertUnitList[$v['ckbm'].'_'.$v['Wlbm']] = [
                        'warehouse_kingdee_code'      => $v['ckbm'],
                        'goods_kingdee_code'          => $v['Wlbm'],
                        'inventory_quantity'          => $v['Dbzkxkc'],
                    ];
                }

                //获取数据库仓库库存信息
                $goodsStockData = [];
                $stockData = Db::name('shop_goods_stock')->where('id','>',0)->field('id,warehouse_kingdee_code,goods_kingdee_code,inventory_quantity')->select();
                if(!$stockData){//没有数据同步库存到数据库
                    $insertUnitList = array_values($insertUnitList);
                    if($insertUnitList){
                        Db::name('shop_goods_stock')->insertAll($insertUnitList);
                    }
                }else{//有数据开始对比 一样的更新，不一样的修改
                    foreach($stockData as $stock){
                        $stockKey = $stock['warehouse_kingdee_code'].'_'.$stock['goods_kingdee_code'];
                        if(isset($insertUnitList[$stockKey])){//存在

                            if($stock['inventory_quantity'] != $insertUnitList[$stockKey]['inventory_quantity']){
                                Db::name('shop_goods_stock')->where('warehouse_kingdee_code','=',$stock['warehouse_kingdee_code'])
                                    ->where('goods_kingdee_code','=',$stock['goods_kingdee_code'])->update(['inventory_quantity' => $insertUnitList[$stockKey]['inventory_quantity'],'update_time' => time()]);
                            }
                            unset($insertUnitList[$stockKey]);
                        }
                    }

                    //如果有新的仓库销售政策库存需要插入数据库
                    if(!empty($insertUnitList)){
                        $insertUnitList = array_values($insertUnitList);
                        if($insertUnitList){
                            Db::name('shop_goods_stock')->insertAll($insertUnitList);
                        }
                    }

                }

            }
            return true;

        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }

    }

    /**
     * 导入销售政策
     * @param $param
     * @return bool
     * @author Mr.Li
     * @create 2021-09-07 13:49
     */
    public function import($param)
    {
        // 验证
        $categoryId = 51;
        $userId = 1;
        $insertGoods = [];
        $goodsType = ['定制' => 0,'标品' => 1];
        $time = time();
        foreach($param as $v){
            $insertGoods[] = [
                'is_standard_product'       => $goodsType[$v[0]] ?? '',
                'name'                      => $v[1] ?? '',
                'desc'                      => $v[2] ?? '',
                'spec_big_name'             => $v[3] ?? '',
                'spec_small_name'           => $v[4] ?? '',
                'unit_code'                 => $v[5] ?? '',
                'small_unit_price'          => $v[6] ?? '',
                'goods_price'                     => $v[7] ?? '',
                'kingdee_stock_unit'        => $v[8] ?? '',
                'kingdee_code'              => $v[9] ?? '',
                'trans_coefficient'         => $v[10] ?? '',
                'sample_unit'               => $v[11] ?? '',
            ];
        }
        try {
            $goodsValidate = new \app\admin\validate\Policy();
            $skuValidate = new \app\admin\validate\PolicySku();
            foreach($insertGoods as $goods){
                if (!$goodsValidate->scene('batch_create')->check($goods)) {
                    $this->error = $goodsValidate->getError();
                    return false;
                }

                if (!$skuValidate->scene('batch_create')->check($goods)) {
                    $this->error = $skuValidate->getError();
                    return false;
                }
            }

        }catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
        $unitCodes = array_column($insertGoods,'unit_code');
        if($unitCodes){
            $unitData = Db::name('shop_goods_unit')->where('big_unit_code','in',$unitCodes)->column('unit_id','big_unit_code');
        }
        $specNames = array_column($insertGoods,'spec_big_name');
        if($specNames){
            $specData = Db::name('shop_goods_spec')->where('name','in',$specNames)->column('item_id','name');
        }
        Db::startTrans();
        $time = time();
        try {
            foreach ($insertGoods as $goods){
                $unitId = $unitData[$goods['unit_code']] ?? '';
                if(!$unitId){
                    throw new \Exception('单位编码不存在,请确认是否正确');
                }
                // 验证
                $data = [
                    'name'                  => trim($goods['name']),
                    'category_id'           => $goods['is_standard_product'] ? 1 : 2 ,
                    'desc'                  => $goods['desc'],
                    'content'               => '',
                    'sort'                  => 0,
                    'thumb_image'           => '',
                    'share_image'           => '',
                    'image'                 => '',
                    'create_user_id'        =>  $userId,
                    'status'                => 1,
                    'update_time'           => $time,
                    'create_time'           => $time,
                    'is_standard_product'   => $goods['is_standard_product']
                ];
                $goodsObj = $this->create($data);
                if ($goodsObj) {
                    $this->addActionRecord(1,'shop_goods_create',$goodsObj->id,'添加销售政策' .$data['name'],'shop','goods');
                }
            }
            $this->error = '添加成功';
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }

}
